# ******** Study the Simulation Results From the Model *******
### Note: the default is that when you call this file, the path is the current file path. "FigurePath" and "TablePath" are paths for figure and table outputs. 

# ------------  Pre-Process the Model Simulated Data -----------------
# Then call the module that processes
option = "general_belief"
source("Codes_Model/preprocessing_simulation_data.R")
# Preprocessing the data 
gen_tables = TRUE
gen_figures = TRUE

#==================== Table: Cross Section Severity for General Beliefs (Appendix) ===================
print("************ Generating Table for Appendix B: Cross Section Severity for General Beliefs ************ ")
reg_output_and_credit_spread <- function( TB ){
  TB[ , crisis_interact_credit_spread_change :=  credit_spread_change*crisis]
  TB[ , crisis_interact_credit_spread_control :=  credit_spread_last_year*crisis]
  TB[  , crisis_interact_bank_credit:= bank_credit_GDP*crisis ]
  regs=list()
  regs[[1]] = lm( 100*GDP_3Y_change ~  crisis_interact_credit_spread_change  , data=TB )
  regs[[2]] = lm( 100*GDP_3Y_change ~  crisis_interact_bank_credit  , data=TB )
  return(regs)
}
latex_reg_output_and_credit_spread_all <- function(regs, dependent_var_name="GDP Growth", vol_vec=c(0.47, 0.16, 0.30)){
  N_columns = length(regs)
  results=capture.output(stargazer( regs , df = FALSE, digits = 2, omit.stat = c("f", "ser","n","adj.rsq") , omit=c("Constant"), star.cutoffs = c(0, 0, 0),
                                    se = list( 0, 0, 0, 0, 0, 0)  ,
                                    title=paste0(dependent_var_name, " and Credit Spread (General Beliefs)"),
                                    label = paste0("Severity regression on ", dependent_var_name)  ,
                                    dep.var.caption= paste0("\\textit{Dependent variable: ", dependent_var_name, " from $t$ to $t+3$}") ,
                                    dep.var.labels =  rep("",N_columns) , 
                                    column.labels   = c("Bayesian","Overoptimistic", "Overpessimistic"),
                                    covariate.labels = c("$\\Delta$credit spread$_t*$crisis$_t$", 
                                                         "$(\\frac{\\text{bank credit}}{\\text{GDP}})_t*$crisis$_t$" ),
                                    column.separate = rep(2,N_columns/2),
                                    notes="To be replaced", notes.append=FALSE, notes.align="l",
                                    column.sep.width = "10pt", no.space = TRUE
  ))
  results[12] = "\\\\[-1.8ex]"
  results[length(results)-2] =  paste0("\\multicolumn{", N_columns+1 ,"}{p{0.95\\textwidth}}{\\footnotesize \\textit{Note}: Model and data regressions are normalized so that the coefficients reflect the impact of one sigma change in spreads, and bank credit/GDP. }")
  writeLines(results, paste0(TablePath,"crisis_aftermath/",gsub(" ", "_", dependent_var_name, fixed = TRUE), "_all_general_belief.tex" ) )
  print(results)
}
regs_Bayesian = reg_output_and_credit_spread(TB_Bayesian)
regs_optimistic= reg_output_and_credit_spread(TB_optimistic)
regs_pessimistic= reg_output_and_credit_spread(TB_pessimistic)
if(gen_tables){
  regs = c(regs_Bayesian, regs_optimistic,  regs_pessimistic )
  latex_reg_output_and_credit_spread_all( regs)
}


#==================== Table: Bank Credidt and Excess Returns for General Beliefs (Appendix B) ===================
print("************ Generating Table for Appendix B:  Bank Credidt and Excess Returns ************ ")
reg_capital_return <- function(TB){
  TB = TB_Bayesian
  TB[, bank_credit_GDP_total := xK*w*p/productivity ]
  regs = list()
  regs[[1]] = lm( capital_excess_return_normalized ~ bank_credit_GDP_total, data = TB)
  return(regs)
}

latex_reg_capital_return_all <- function(regs, vol_vec = c(0.0095)){
  results=capture.output(stargazer( regs , df = FALSE, digits = 2, omit.stat = c("f", "ser","n","adj.rsq","LL","aic") , omit=c("Constant"), star.cutoffs = c(0, 0, 0),
                                    se = list( 0, 0, 0 )  ,
                                    title=paste0("Bank Credit Predicting Capital Excess Returns (General Beliefs)"),
                                    label = paste0("bank credit and excess returns")  , 
                                    dep.var.caption=  "\\textit{Dependent variable:}" ,
                                    dep.var.labels =  "Average realized excess return $_{t+1}$" , 
                                    covariate.labels = c("$(\\frac{\\text{bank credit}}{\\text{GDP}})_t$"),
                                    column.separate = c(1, 1, 1), 
                                    add.lines =  list(  c( "Observations", rep("",3), "867" )  ),
                                    notes="To be replaced", notes.append=FALSE, notes.align="l",
                                    column.sep.width = "10pt", no.space = TRUE
  ))
  results[13] = "\\\\[-1.8ex] & (1) Rational & (2) Optimistic & (3) Pessimistic \\\\"
  results[length(results)-2] =  "\\multicolumn{4}{p{0.9\\textwidth}}{\\footnotesize \\textit{Note}: 
  Model excess return is defined as the return to capital minus the risk-free rate. Data excess return is the excess 
equity index return from Online Appendix Table 3 of Baron and Xiong (2017). To ensure comparability, the model return 
to capital has been normalized to equal the standard deviation of returns reported by Baron and Xiong (2017).
}  "
  writeLines(results, paste0(TablePath,"capital_excess_returns/credit_and_capital_return_general_belief.tex" ) )
  print(results)
}
regs_Bayesian = reg_capital_return(TB_Bayesian)
regs_optimistic = reg_capital_return(TB_optimistic)
regs_pessimistic = reg_capital_return(TB_pessimistic)

if(gen_tables){
  regs = c( regs_Bayesian,  regs_optimistic, regs_pessimistic )
  latex_reg_capital_return_all( regs )
}





